import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import { UserModule } from '@/store/modules/user'
import common from './common'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 20000,
  timeoutErrorMessage: '请求超时',
  // withCredentials: true // send cookies when cross-domain requests
})

// Request interceptors
service.interceptors.request.use(
  (config) => {
    // Add X-Access-Token header to every request, you can add other custom headers here
    if (UserModule.token) {
      config.headers['X-Access-Token'] = UserModule.token
      config.headers.Authorization = 'Bearer ' + UserModule.token
    }
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

let env = ''

// Response interceptors
service.interceptors.response.use(
  (response) => {
    // Some example codes here:
    // code == 20000: success
    // code == 50001: invalid access token
    // code == 50002: already login in other place
    // code == 50003: access token expired
    // code == 50004: invalid user (user not exist)
    // code == 50005: username or password is incorrect
    // You can change this part for your own usage.
    if (response.headers.env && response.headers.env !== env) {
      env = response.headers.env
      const text =
        env === 'Development' ? '开发环境' : env === 'Staging' ? '测试环境' : ''
      Message({
        message: `当前为${text}, 数据与线上环境不同步`,
        type: 'warning',
        duration: 0,
        showClose: true,
      })
    }

    const res = response.data
    if (res.code !== 20000) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5000,
      })
      if (res.code === 50001) {
        userLogout('无效的登陆信息，需要重新登录')
      } else if (res.code === 50002) {
        userLogout('账号已在其他设备登陆，需要重新登录')
      } else if (res.code === 50003) {
        userLogout('登陆信息已失效，需要重新登录')
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return response.data
    }
  },
  (error) => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5000,
    })
    return Promise.reject(error)
  }
)

const userLogout = (message) => {
  MessageBox.confirm(message, '确定登出', {
    confirmButtonText: '重新登录',
    cancelButtonText: '取消',
    showCancelButton: false,
    type: 'warning',
  }).then(() => {
    UserModule.ResetToken()
    if (common.IsInExe()) {
      common.ExeInvoke((f) => {
        f.Exit()
      })
    } else {
      location.reload() // To prevent bugs from vue-router
    }
  })
}

export default service
